package com.lkd.handler;

import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.lkd.business.MsgHandler;
import com.lkd.config.TopicConfig;
import com.lkd.contract.SupplyChannel;
import com.lkd.contract.SupplyContract;
import com.lkd.emq.Topic;
import com.lkd.entity.ChannelEntity;
import com.lkd.service.ChannelService;
import com.lkd.utils.JsonUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

@Component
@Topic(TopicConfig.VMS_COMPLETED_TOPIC)
public class TaskSupplyHandler implements MsgHandler {
    @Autowired
    private ChannelService channelService;
    @Override
    public void process(String jsonMsg) throws IOException {
        SupplyContract supplyContract = JsonUtil.getByJson(jsonMsg, SupplyContract.class);
        //获取机器编号
        String innerCode = supplyContract.getInnerCode();
        //获取消息中的补货数据
        List<SupplyChannel> list = supplyContract.getSupplyData();

        List<ChannelEntity> channelEntities = new ArrayList<>();
        //遍历该机器，获取每个货道的补货数据
        for (SupplyChannel supplyChannel : list) {
            //根据机器编号获取货道实体对象
            LambdaQueryWrapper<ChannelEntity> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(ChannelEntity::getInnerCode, innerCode);
            ChannelEntity channelEntity = channelService.getOne(queryWrapper);
            //获取货道补货前容量
            Integer currentCapacity = channelEntity.getCurrentCapacity();
            //获取工单中新增的容量
            int capacity = supplyChannel.getCapacity();
            //当前容量为补货前容量+新增容量
            capacity= currentCapacity+capacity;
            //更新货道容量
            channelEntity.setCurrentCapacity(capacity);
            //将更新后的货道实体类对象添加到集合中
            channelEntities.add(channelEntity);
        }

        //更新补货数据
        channelService.updateBatchById(channelEntities);
    }
}
